﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Angel.Daos.IManager;
using Angel.Entities;

namespace Angel.Daos.Manager
{
    public class RoleManager : IRoleManager
    {
        AngelDataContext ctx = new AngelDataContext();
        public IEnumerable<Role> GetAll()
        {
            return ctx.Roles.OrderBy(m => m.Name);
        }
        public Boolean Add(Role role)
        {
            //return true if Add successful or return false if not complete.
            Role source = ctx.Roles.OrderBy(m => m.Name).SingleOrDefault(m => m.Name == role.Name);
            if (source == null)
            {
                ctx.Roles.InsertOnSubmit(role);
                ctx.SubmitChanges();
                return true;
            }
            else
            {
                return false;
            }
        }
        public Role GetById(int RoleId)
        {
            return ctx.Roles.SingleOrDefault(r => r.ID == RoleId);
        }
        

        public void Delete(Role role)
        {
            //ctx.Roles.Attach(role);
            ctx.Roles.DeleteOnSubmit(role);
            ctx.SubmitChanges();
        }

        public void Delete(long roleId)
        {
            
        }

        public void Save(Role role)
        {
            ctx.SubmitChanges();
        }


        public bool CheckNameExist(string name,int id)
        {
            var role=ctx.Roles.SingleOrDefault(n=>n.Name==name.Trim());
            if (role == default(Role))//not found
                return false;
            else
                if (role.ID == id)
                    return false;
                else 
                    return true;
        }
    }
}
